<!--文件管理-->
<template>
  <div id="documentExplorer" class="app-container flex-row">
    <div class="conmmon-container-left" style="width:200px;border-right: 1px solid #E6E6E6;">
      <el-tree
        v-loading="treeLoading"
        class="common-el-tree scrollbar-no-width"
        node-key="id"
        :default-expanded-keys="['-1','-2']"
        :props="fileCatalogProps"
        :load="loadFileCatalog"
        lazy
        :expand-on-click-node="false"
        @node-click="handleCatalogNodeClick">
        <div slot-scope="{ node,data }" class="custom-tree-node">
          <file-catalog-svg-icon :type="data.catalogType" />
          <template v-if="data.catalogType==-3">
            <file-type-svg-icon :type="data.fileType" />
          </template>
          <span class="text">{{ node.label }}</span>
        </div>
      </el-tree>
    </div>
    <div class="conmmon-container-main flex-main">
      <component :is="componentName" :catalog-id="catalogId" :node="selectedNodeData" :file-path="fileFullPath" @handleEvent="handleEvent" />
    </div>
    <!--新建文件夹-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" :before-close="handleClose">
      <el-form ref="dataForm" :rules="fileCatalogRule" :model="fileCatalogConfigRecord" label-position="right" label-width="180px">
        <el-form-item label="文件夹名称" prop="catalogName">
          <el-input v-model="fileCatalogConfigRecord.catalogName" maxlength="10" show-word-limit placeholder="请输入文件夹名称" />
        </el-form-item>
        <el-form-item label="文件夹路径" prop="catalogPath">
          <el-input v-model="fileCatalogConfigRecord.catalogPath" maxlength="20" show-word-limit placeholder="请输入文件夹路径" />
        </el-form-item>
        <el-form-item label="是否加密" prop="isEncryption">
          <el-radio v-model="fileCatalogConfigRecord.isEncryption" label="0">不加密</el-radio>
          <el-radio v-model="fileCatalogConfigRecord.isEncryption" label="1">加密</el-radio>
        </el-form-item>
        <el-form-item v-if="fileCatalogConfigRecord.isEncryption=='1'" label="密码" prop="encryptionPassword">
          <el-input v-model="fileCatalogConfigRecord.encryptionPassword" maxlength="8" show-word-limit type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="是否允许新建文件夹" prop="isAllowNewFolder">
          <el-radio v-model="fileCatalogConfigRecord.isAllowNewFolder" label="0">不允许</el-radio>
          <el-radio v-model="fileCatalogConfigRecord.isAllowNewFolder" label="1">允许</el-radio>
        </el-form-item>
        <el-form-item label="是否只读" prop="isAllowRead">
          <el-radio v-model="fileCatalogConfigRecord.isAllowRead" label="0">可读</el-radio>
          <el-radio v-model="fileCatalogConfigRecord.isAllowRead" label="1">只读</el-radio>
        </el-form-item>
        <el-form-item label="是否允许删除" prop="isAllowDeleted">
          <el-radio v-model="fileCatalogConfigRecord.isAllowDeleted" label="0">不允许</el-radio>
          <el-radio v-model="fileCatalogConfigRecord.isAllowDeleted" label="1">允许</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="newFolder()">确定</el-button>
      </div>
    </el-dialog>
    <!--验证密码-->
    <el-dialog :visible.sync="checkPassword.recordShow" :close-on-click-modal="false" title="请输入加密文件密码" width="300px">
      <el-input v-model="checkPassword.password" placeholder="请输入密码" auto-complete="off" show-password />
      <div slot="footer" class="dialog-footer">
        <el-button :loading="checkPassword.buttonLoading" type="primary" @click="handleCheckPassword()">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import document from './document'
import recyle from './recyle'

export default {
  components: { document, recyle },
  data() {
    return {
      treeLoading: false,
      fileCatalogProps: {
        label: 'catalogName',
        children: 'catalogs',
        isLeaf: 'leaf'
      },
      componentName: 'document',
      catalogId: '',
      selectedNode: {},
      fileFullPath: [],
      selectedNodeData: {},
      tempCurrentNode: null,
      fileCatalogConfigRecord: {
        catalogName: '',
        catalogPath: '',
        catalogPid: '',
        isEncryption: '0',
        encryptionPassword: '',
        isAllowNewFile: '1',
        isAllowNewFolder: '1',
        isAllowRead: '0',
        isAllowDeleted: '1'
      },
      fileCatalogRule: {
        catalogName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        catalogPath: [
          { required: true, message: '请输入路径', trigger: 'blur' },
          { validator: this.commonValidate.validateEngOrNum, trigger: 'blur' }
        ],
        isEncryption: [
          { required: true, message: '是否加密', trigger: 'blur' }
        ],
        isAllowNewFile: [
          { required: true, message: '是否允许新建文件', trigger: 'blur' }
        ],
        isAllowNewFolder: [
          { required: true, message: '是否允许新建文件夹', trigger: 'blur' }
        ],
        isAllowRead: [
          { required: true, message: '是否只读', trigger: 'blur' }
        ],
        isAllowDeleted: [
          { required: true, message: '是否允许删除', trigger: 'blur' }
        ]
      },
      buttonLoading: false,
      dialogVisible: false, // 对话框是否可见
      dialogTitle: '新建文件夹',
      passwordVisible: false, // 密码验证对话框
      reNameVisible: false, // 重命名对话框
      checkPassword: {
        recordShow: false,
        buttonLoading: false,
        password: ''
      }

    }
  },
  mouted() {},
  watch: {

  },
  created() {
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        }).catch(_ => {})
    },
    async loadFileCatalog(node, resolve) {
      try {
        this.treeLoading = true
        if (node.level === 0) {
          const caltalogs = [
            { id: '-1', catalogName: '位置', catalogType: -1 }
          ]
          resolve(caltalogs)
        } else if (node.level === 1) {
          var id = node.data.id
          if (id === '-1') {
            const catalogResponse = await this.$store.dispatch('listFileCatalogByPid', { pid: '0' })
            var catalogs = catalogResponse.filter(item => {
              return item.catalogType !== 9
            })
            if (catalogs.length === 0) {
              this.initDocsCatalog()
            } else {
              var temp = catalogs[0]
              this.fileFullPath = []
              this.fileFullPath.push({ id: temp.id, catalogName: temp.catalogName, catalogType: temp.catalogType })
              if (temp.catalogType === 5) {
                this.componentName = 'recyle'
              } else {
                this.componentName = 'document'
              }
              this.$nextTick(() => {
                this.catalogId = temp.id
                this.selectedNodeData = temp
              })
            }
            resolve(catalogs)
          }
        } else {
          const catalogResponse = await this.$store.dispatch('listFileCatalogByPid', { pid: node.data.id })
          resolve(catalogResponse)
        }
        this.treeLoading = false
      } catch (err) {
        console.log(err)
      }
    },
    initDocsCatalog() {
      this.$alert('您还初始化文件目录,请先进行初始化', '警告', {
        showClose: false,
        confirmButtonText: '初始化',
        callback: action => {
          this.$store.dispatch('initDocsCatalog', {}).then((res) => {
            this.msgSuccess('初始化成功')
            window.location.reload()
          }).catch((_) => {})
        }
      })
    },
    handleCatalogNodeClick(data, node) {
      if (node.level === 1) {
        return
      }
      this.fileFullPath = []
      this.getAllPath(node)
      this.fileFullPath.reverse(this.fileFullPath)
      var firstLevelCatalogType = this.fileFullPath[0].catalogType
      if (this.fileFullPath.length === 1 && firstLevelCatalogType === 5) {
        this.msgWarning('请选择子节点')
        return
      }
      console.log(111)
      this.$nextTick(() => {
        if (data.isEncryption === -1) {
          this.fileFullPath = [{ catalogType: -100 }]
          this.tempCurrentNode = node
          this.checkPassword.recordShow = true
          this.checkPassword.id = data.id
          this.checkPassword.password = ''
        } else {
          this.catalogId = data.id
          this.selectedNode = node
          this.selectedNodeData = data
          this.fileFullPath = []
          this.getAllPath(node)
          this.fileFullPath.reverse(this.fileFullPath)
        }
        if (firstLevelCatalogType === 5) {
          this.componentName = 'recyle'
        } else {
          this.componentName = 'document'
        }
      })
    },
    getAllPath(node) {
      if (node) {
        if (node.level !== 1) {
          this.fileFullPath.push({ id: node.data.id, catalogName: node.data.catalogName, catalogType: node.data.catalogType })
          this.getAllPath(node.parent)
        }
      }
    },
    handleEvent(e) {
      if (!this.catalogId) {
        this.msgWarning('此文件夹不允许操作!')
        return
      }
      if (e === 'newFolder') {
        this.handleCreateFolder()
      }
      if (e === 'removeFolder') {
        this.handleRemoveFolder()
      }
    },
    /* 新增*/
    handleCreateFolder() {
      this.resetFileCatalogConfigRecords()
      this.fileCatalogConfigRecord.catalogPid = this.catalogId
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    newFolder() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.buttonLoading = true
          this.$store.dispatch('saveFileCatalog', this.fileCatalogConfigRecord).then(response => {
            this.dialogVisible = false
            this.buttonLoading = false
            this.msgSuccess('添加成功')
            this.refreshTreeNode(this.selectedNode, this.catalogId)
          }).catch(() => {
            this.buttonLoading = false
          })
        }
      })
    },
    handleRemoveFolder() {
      var data = this.selectedNode.data
      if (!data) {
        this.msgWarning('请选择文件夹')
        return
      }
      if (data.isBuiltIn === 1) {
        this.msgWarning('内置文件夹无法删除')
        return
      }
      if (data.isEncryption === '1') {
        this.msgWarning('加密文件夹无法删除')
        return
      }
      if (data.isAllowDeleted === '0') {
        this.msgWarning('此文件夹不允许删除')
        return
      }
      this.$confirm(`此操作将永久删除文件夹[${data.catalogName}], 是否继续?`, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('removeFileCatalog', { id: data.id }).then(response => {
          this.msgSuccess('操作成功')
          if (this.selectedNode.parent) {
            this.refreshTreeNode(this.selectedNode.parent, this.selectedNode.parent.data.id)
          }
        }).catch(() => {})
      }).catch(() => {})
    },
    async refreshTreeNode(node, catalogId) {
      node.childNodes = []
      const catalogResponse = await this.$store.dispatch('listFileCatalogByPid', { pid: catalogId })
      node.doCreateChildren(catalogResponse)
    },
    handleCheckPassword() {
      if (!this.checkPassword.password) {
        this.msgWarning('请输入密码！')
        return
      }
      this.checkPassword.buttonLoading = true
      this.$store.dispatch('checkFileCatalogPassword', { id: this.checkPassword.id, password: this.checkPassword.password })
        .then(response => {
          this.checkPassword.recordShow = false
          this.checkPassword.buttonLoading = false
          this.catalogId = this.tempCurrentNode.data.id
          this.selectedNode = this.tempCurrentNode
          this.selectedNodeData = this.tempCurrentNode.data
          this.fileFullPath = []
          this.getAllPath(this.tempCurrentNode)
          this.fileFullPath.reverse(this.fileFullPath)
        })
        .catch(() => {
          this.checkPassword.buttonLoading = false
        })
    },

    resetFileCatalogConfigRecords() {
      this.fileCatalogConfigRecord = {
        catalogPid: this.catalogId,
        isEncryption: '0',
        isAllowNewFile: '1',
        isAllowNewFolder: '1',
        isAllowRead: '0',
        isAllowDeleted: '1'
      }
    }

  }
}
</script>

<style lang="scss" >
  #documentExplorer{
    .common-el-tree{
      .text{
        font-size: 12px;
      }
      .el-tree-node__content {
        height: 36px;
        line-height: 36px;
      }
    }
  }
</style>
